package com.xuecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.service.RegisterService;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.mapper.XcUserRoleMapper;
import com.xuecheng.ucenter.model.dto.RegisterDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.model.po.XcUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Random;

/**
 * @author 陈竞超
 * @version 1.0
 * @qq 2250537249
 */
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    XcUserRoleMapper xcUserRoleMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    @Transactional
    public RegisterDto createUser(RegisterDto registerDto) {
        if (registerDto == null){
            throw new XueChengPlusException("输入信息为空");
        }
        Object checkcode = redisTemplate.opsForValue().get("checkcode");
        if (checkcode.toString().equals(registerDto.getCheckcode())) {
            XcUser xcUser = new XcUser();
            String id = String.valueOf(new Random().nextInt(100000));
            xcUser.setId(id);
            xcUser.setCellphone(registerDto.getCellphone());
            xcUser.setUsername(registerDto.getUsername());
            xcUser.setNickname(registerDto.getNickname());
            xcUser.setName(registerDto.getNickname());
            xcUser.setUtype(String.valueOf(101001));
            xcUser.setStatus(String.valueOf(1));
            xcUser.setCreateTime(LocalDateTime.now());
            xcUser.setEmail(registerDto.getEmail());
            String encode = passwordEncoder.encode(registerDto.getPassword());
            xcUser.setPassword(encode);
            xcUserMapper.insert(xcUser);

            XcUserRole xcUserRole = new XcUserRole();
            xcUserRole.setId(String.valueOf(new Random().nextInt(100000)));
            xcUserRole.setUserId(id);
            xcUserRole.setRoleId(String.valueOf(17));

            xcUserRoleMapper.insert(xcUserRole);
            redisTemplate.delete("checkcode");
            return registerDto;
        }
        return null;
    }
}
